package com.cwg.dict.service.impl;

import org.apache.commons.lang.StringUtils;

public class NearWordSelector {

	private String[]	words;

	public NearWordSelector(String[] words) {
		this.words = words;
	}

	public String selectWordNearTo(String input) {
		int maxMatchLength = 0;
		String maxMatchWord = "";
		for (String each : words) {
			if (StringUtils.equalsIgnoreCase(each, input)) {
				return each;
			} else if (StringUtils.startsWith(each, input) || StringUtils.startsWith(input, each)) {
				if (matchLength(each, input) > maxMatchLength) {
					maxMatchLength = matchLength(each, input);
					maxMatchWord = each;
				}
			}
		}
		return maxMatchWord;
	}

	protected int matchLength(String str1, String str2) {
		String s1;
		String s2;
		if (str1.length() >= str2.length()) {
			s1 = str1.toLowerCase();
			s2 = str2.toLowerCase();
		} else {
			s1 = str2.toLowerCase();
			s2 = str1.toLowerCase();
		}
		if (s1.length() == s2.length() && StringUtils.endsWithIgnoreCase(s1, s2)) {
			return s1.length();
		}
		if (s1.length() >= s2.length()) {
			if (0 == StringUtils.indexOfDifference(s1, s2)) {
				return -1;
			} else {
				return StringUtils.indexOfDifference(s1, s2);
			}
		}
		return 0;
	}
}
